package com.world.cat.service.sys;

import com.world.cat.dao.sys.TokenInfoDao;
import com.world.cat.model.sys.Token;
import com.world.common.util.CollectionUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by gang on 2016/8/2.
 */
@Service
@Transactional
public class TokenInfoService {
    public static Map<String, String> tokenMap = new ConcurrentHashMap<>();

    @Resource
    private TokenInfoDao tokenInfoDao;

    public void saveTokenLog(String name, String token) {
        Token sysToken = tokenInfoDao.findByTokenKey(name);
        if (sysToken != null) {
            sysToken.setTokenValue(token);
        } else {
            sysToken = new Token();
            sysToken.setTokenKey(name);
            sysToken.setTokenValue(token);
        }
        tokenInfoDao.save(sysToken);
    }

    public List<Token> findAll() {
        return tokenInfoDao.findAll();
    }

    public void initCache() {
        List<Token> tokens = tokenInfoDao.findAll();
        if (CollectionUtil.isNotEmpty(tokens)) {
            for (Token token : tokens) {
                tokenMap.put(token.getTokenKey(), token.getTokenValue());
            }
        }
    }
}
